package util

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

func ParseJwtToken(signedToken, secret string) (*jwt.StandardClaims, error) {

	claims := &jwt.StandardClaims{}
	_, err := jwt.ParseWithClaims(signedToken, claims, func(*jwt.Token) (interface{}, error) {
		return []byte(secret), nil
	})
	if err != nil {
		return nil, fmt.Errorf("jwt token invalid")
	}
	if time.Now().After(time.Unix(claims.ExpiresAt, 0)) {
		return nil, fmt.Errorf("jwt token expire")
	}

	return claims, nil
}


func GenJwkTokenV2(bizID string, typ int, secret string, expire time.Duration) (string, error) {
	claims := &jwt.StandardClaims{
		Id:        bizID,
		Subject:   ToString(typ),
		ExpiresAt: time.Now().Add(expire).Unix(),
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	signedToken, err := token.SignedString([]byte(secret))
	if err != nil {
		return "", fmt.Errorf("sign error:%s", err.Error())
	}
	return signedToken, nil
}
